import pyhdfs


# 操作HDFS类
class HDFS:
    # 初始化连接服务器的参数
    def __init__(self, host='192.168.62.72', user_name='root'):
        self.host = host
        self.user_name = user_name

    # 连接HDFS服务器
    def getCon(self):
        try:
            conHdfs = pyhdfs.HdfsClient(hosts=self.host, user_name=self.user_name)
            return conHdfs
        except pyhdfs.HdfsException as e:
            # 打印错误信息
            print("连接错误：%s" % e)

    # 获取当前指定目录的文件信息
    def getListDir(self, dirname):
        try:
            clientCon = self.getCon()
            # 获取目录中的信息
            dirList = clientCon.listdir(dirname)
            # 打印信息
            for row in dirList:
                print(row)
        except pyhdfs.HdfsException as e:
            # 打印错误信息
            print("获取错误：%s" % e)

    # 创建文件夹
    def createDir(self, dirname):
        try:
            clientCon = self.getCon()
            # 创建文件夹
            name = clientCon.mkdirs(dirname)
            print(name)
        except pyhdfs.HdfsIOException as e:
            # 打印错误信息
            print("创建文件夹时错误：%s" % e)
        except pyhdfs.HdfsException as e:
            # 打印错误信息
            print("操作文件夹时错误：%s" % e)

    # 上传文件
    def uploadFile(self, localName, hdfsName):
        try:
            clientCon = self.getCon()
            # 上传文件
            clientCon.copy_from_local(localName, hdfsName)
        except pyhdfs.HdfsException as e:
            # 打印错误信息
            print("上传时错误：%s" % e)
        except pyhdfs.HdfsIOException as e:
            # 打印错误信息
            print("上传文件时错误：%s" % e)

    # 读取文件
    def readFile(self, FileUrlName):
        try:
            clientCon = self.getCon()
            # 读取文件内容
            readFile = clientCon.open(FileUrlName)
            fileData = readFile.read()
            # 打印文件内容
            print(fileData)
        except pyhdfs.HdfsException as e:
            # 打印错误信息
            print("读信息时报错：%s" % e)
        except pyhdfs.HdfsIOException as e:
            # 打印错误信息
            print("读取文档时出错：%s" % e)

    # 确认文件是否存在
    def isFile(self, FileUrlName):
        try:
            clientCon = self.getCon()
            # 确认文件是否存在
            isFile = clientCon.exists(FileUrlName)
            return isFile
        except pyhdfs.HdfsIOException as e:
            # 打印错误信息
            print("判断文件出错时出错：%s" % e)

    # 删除文件
    def deleteFile(self, FileUrlName):
        try:
            clientCon = self.getCon()
            # 删除指定文件
            delFile = clientCon.delete(FileUrlName)
            return delFile
        except pyhdfs.HdfsIOException as e:
            # 打印错误信息
            print("删除文件时错误：%s" % e)
        except pyhdfs.HdfsException as e:
            # 打印错误信息
            print("删除信息时报错：%s" % e)
